<?php

/**
 * This is the model class for table "{{song}}".
 *
 * The followings are the available columns in table '{{song}}':
 * @property integer $id
 * @property string $title
 * @property string $singer
 * @property string $body
 * @property integer $create_time
 * @property integer $update_time
 * @property integer $status
 * @property integer $view
 * @property integer $is_trade
 * @property integer $user_id
 * @property integer $is_validated
 * @property String $embed_code
 * @property String $guitar_tabs
 *
 * The followings are the available model relations:
 * @property User $user
 */
class Song extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Song the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{song}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
            array('title, body', 'required'),
			array('create_time, update_time, status, view, is_trade, user_id', 'numerical', 'integerOnly'=>true),
			array('title, singer', 'length', 'max'=>255),
			array('body,embed_code,is_validated,guitar_tabs', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, title, singer, body, create_time, update_time, status, view, is_trade, user_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
            'comments' => array(self::HAS_MANY, 'Comments', 'item_id','condition'=>"status=1 AND item_type='song'"),
            'commentCount' => array(self::STAT, 'Comments', 'item_id', 'condition'=>"status=1 AND item_type='song'"),
            'rate' => array(self::HAS_MANY, 'SongRate', 'song_id'),
            'rateCount' => array(self::STAT, 'SongRate', 'song_id'),
            'ownrateCount' => array(self::STAT, 'SongRate', 'song_id','condition'=>'user_id='.Yii::app()->user->id),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Tên bản nhạc',
			'singer' => 'Ban nhạc/Ca sĩ',
			'body' => 'Lời',
			'create_time' => 'Ngày đăng',
			'update_time' => 'Ngày cập nhật',
			'status' => 'Trạng thái',
			'view' => 'Lượt xem',
			'is_trade' => 'Thu phí?',
			'is_validated' => 'Kiểm duyệt',
			'embed_code' => 'Mã nhúng',
			'user_id' => 'Người đăng',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('singer',$this->singer,true);
		$criteria->compare('body',$this->body,true);
		$criteria->compare('create_time',$this->create_time);
		$criteria->compare('update_time',$this->update_time);
		$criteria->compare('status',$this->status);
		$criteria->compare('view',$this->view);
		$criteria->compare('is_trade',$this->is_trade);
		$criteria->compare('user_id',$this->user_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

    public function beforeSave()
    {
        if($this->isNewRecord){
            $this->create_time = time();
            $this->update_time = time();

            if(!Yii::app()->user->isGuest){
                $this->user_id = Yii::app()->user->id;
            }
        }
        else
        {
            $this->update_time = time();
        }
        return parent::beforeSave();
    }

    /**
     * @param $comment Comments
     * @return mixed
     */
    public function addComment($comment)
    {
        if(Yii::app()->params['commentNeedApproval'])
            $comment->status=2;
        else
            $comment->status=1;
        $comment->item_type = 'song';
        $comment->item_id=(int)$this->id;
        return $comment->save();
    }

    public function getUrl()
    {
        return Yii::app()->createUrl('song/view', array(
            'id'=>$this->id,
            'title'=>$this->title,
        ));
    }
    function getStar(){
        if($this->rateCount > 0){

            return $this->averrate/2;
        }
        return 1;
    }
    function getAverrate(){
        if($this->rateCount > 0){
            $total = 0;
            foreach($this->rate as $rate){
                $total += $rate->marks;
            }
            return round($total/$this->rateCount,2);
        }
        return 0;
    }
}